package server;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import unit.ProtocolUnit;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;

/**
 * @author Yuri Denison
 * @since 04.08.11
 */
public class Connector {
    private Socket socket = null;
    private JsonWriter writer = null;
    private JsonReader reader = null;
    private Gson gson = null;

    private static final int SOCKET_TIMEOUT = 10000;
    private static final String ENCODING = "UTF-8";

    public Connector(String host, int port) throws IOException {
        this(new Socket(host, port));
    }

    public Connector(Socket socket) throws IOException {
        this.socket = socket;
        socket.setSoTimeout(SOCKET_TIMEOUT);
        gson = new Gson();
        this.writer = new JsonWriter(new OutputStreamWriter(socket.getOutputStream()));
        this.writer.flush();
    }

    public void send(ProtocolUnit unit) throws IOException {
        writer.beginObject();
        gson.toJson(unit, ProtocolUnit.class, writer);
        writer.endObject();
        writer.flush();
    }

    public ProtocolUnit read() throws IOException, SocketException {
        if (reader == null) {
            reader = new JsonReader(new InputStreamReader(socket.getInputStream(), ENCODING));
        }
        reader.beginObject();
        ProtocolUnit unit = gson.fromJson(reader, ProtocolUnit.class);
        reader.endObject();
        return unit;
    }
}
